package com.snail.auth.service;

import com.common.entity.Page;
import com.common.util.StringUtil;
import com.snail.auth.dao.AuthRoleRep;
import com.snail.auth.entity.AuthRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 系统角色信息Service
 */
@Service
@Transactional
public class AuthRoleService {
    @Autowired
    private AuthRoleRep roleRep;

    public void save(AuthRole entity) {
        if (entity.getFlag() == null) {
            entity.setFlag(0);
        }
        roleRep.saveAndFlush(entity);
    }


    public AuthRole getByKey(Long id) {
        Optional optional = roleRep.findById(id);
        if (optional.isPresent()) {
            return (AuthRole) optional.get();
        }
        return null;
    }

    public Page page(Page page, Map<String, Object> params) {
        StringBuilder sql = new StringBuilder("select r.id, r.name, r.group_id, rg.name as groupName " +
                " from auth_role r, auth_role_group rg " +
                " where r.group_id = rg.id and r.flag=0 ");
        if (!StringUtil.isEmpty(params.get("keyword"))) {
            sql.append(" and r.name like '%" + params.get("keyword").toString().trim() + "%'");
        }
        return roleRep.execSqlPage(page, sql.toString());
    }

    public void del(Long id) {
        roleRep.deleteById(id);
    }

    /**
     * 获取符合element使用的多级结构树
     */
    public List<Map<String, Object>> treeData() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> groups = roleRep.execSql("select id, name, 0 as groupId from auth_role_group");

        List<Map<String, Object>> datas = roleRep.execSql("select g.id as groupId, g.name as groupName, r.id, r.name " +
                " from auth_role r, auth_role_group g " +
                " where g.id = r.group_id and flag=0 order by r.id ");
        Map<String, List<Map<String, Object>>> midMap = new LinkedHashMap<>();
        for (Map<String, Object> data : datas) {
            if (!midMap.containsKey(data.get("groupId").toString())) {
                midMap.put(data.get("groupId").toString(), new ArrayList<Map<String, Object>>());
            }
            midMap.get(data.get("groupId").toString()).add(data);
        }
        for (Map<String, Object> group : groups) {
            group.put("children", midMap.get(group.get("id").toString()));
            group.put("id", "group_" + group.get("id").toString());
            result.add(group);
        }

        return result;
    }

}